package com.factory.manager.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.factory.common.bean.User;
import com.factory.common.core.BaseService;
import com.factory.common.core.ValidateType;
import com.factory.common.pojo.Result;
import com.factory.common.utils.StringUtil;
import com.factory.manager.pojo.UserPojo;
import com.factory.manager.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

@Slf4j
@RestController
@RequestMapping("/manager/user")
public class UserController extends BaseController<UserPojo>{

    @Autowired
    private UserService userService;

    @Override
    protected BaseService getBaseService() {
        return userService;
    }

    /**
     *添加用户的接口
     * @return 用户列表
     */

    public Result insert(@RequestBody UserPojo t) {
        log.info("通用的添加数据方法,{}", t);
        //校验
        Optional<Result> validate = t.validate(ValidateType.INSERT);
        if (validate.isPresent()) {
            return validate.get();
        }

        if(null != userService.selectOne(new QueryWrapper<User>().eq("account",t.getAccount()).ge("status",0)))
            return Result.fail("账号已经被注册!");

        if(StringUtil.notEmpty(t.getMobile())
            && null != userService.selectOne(
                    new QueryWrapper<User>().eq("mobile",t.getMobile()).ge("status",0)))
            return Result.fail("手机号已经被使用!");

        Integer result = getBaseService().insert(t);
        if (1 == result) {
            return Result.success("", null);
        }

        return Result.fail(500, "insert fail!");
    }

}
